package com.liyuxiang.graph.node;

import com.alibaba.cloud.ai.graph.OverAllState;
import com.alibaba.cloud.ai.graph.action.NodeAction;
import com.liyuxiang.graph.service.IntentRecognitionService;
import com.liyuxiang.graph.service.DiagnosisContextService;
import com.liyuxiang.graph.context.DiagnosisContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

public class IntentRecognitionNode implements NodeAction {
    
    private static final Logger logger = LoggerFactory.getLogger(IntentRecognitionNode.class);
    private final IntentRecognitionService intentRecognitionService;
    private final DiagnosisContextService contextService;
    
    public IntentRecognitionNode(IntentRecognitionService intentRecognitionService, DiagnosisContextService contextService) {
        this.intentRecognitionService = intentRecognitionService;
        this.contextService = contextService;
    }
    
    @Override
    public Map<String, Object> apply(OverAllState state) throws Exception {
        String query = state.value("query", "");
        String userId = state.value("userId", "unknown");
        String threadId = state.value("threadId", "unknown");
        
        // 实时从Redis获取对话历史，不依赖OverAllState
        List<String> realTimeHistory = List.of();
        Optional<DiagnosisContext> contextOpt = contextService.getContext(threadId);
        if (contextOpt.isPresent()) {
            realTimeHistory = contextOpt.get().getConversationHistory();
        }
        
        logger.info("开始意图识别 - 用户ID: {}, 输入长度: {}, 实时历史轮次: {}", 
                userId, query.length(), realTimeHistory.size());
        logger.info("用户输入内容: {}", query);
        
        try {
            // 使用AI意图识别服务进行分析，使用实时历史
            IntentRecognitionService.IntentAnalysisResult analysisResult = 
                    intentRecognitionService.analyzeIntent(query, realTimeHistory, userId);
            
            // 记录详细的意图分析信息
            logger.info("意图识别详情 - 类型: {}, 置信度: {}, 风险级别: {}", 
                    analysisResult.getIntent(), analysisResult.getConfidence(), analysisResult.getRiskLevel());
            logger.info("判断理由: {}", analysisResult.getReason());
            logger.info("关键词: {}, 医疗术语: {}", 
                    String.join(",", analysisResult.getKeywords()),
                    String.join(",", analysisResult.getMedicalTerms()));
            
            // 检查是否是扩展结果，包含直接推荐信息
            boolean shouldSkipSymptomCollection = false;
            boolean directRecommendation = false;
            String conversationStage = "";
            String nextAction = "";
            
            if (analysisResult instanceof IntentRecognitionService.ExtendedIntentAnalysisResult) {
                IntentRecognitionService.ExtendedIntentAnalysisResult extendedResult = 
                    (IntentRecognitionService.ExtendedIntentAnalysisResult) analysisResult;
                shouldSkipSymptomCollection = extendedResult.isShouldSkipSymptomCollection();
                directRecommendation = extendedResult.isDirectRecommendation();
                conversationStage = extendedResult.getConversationStage();
                nextAction = extendedResult.getNextAction();
                
                logger.info("扩展意图信息 - 跳过症状收集: {}, 直接推荐: {}, 对话阶段: {}, 下一步行动: {}", 
                    shouldSkipSymptomCollection, directRecommendation, conversationStage, nextAction);
            }
            
            // 特殊处理直接挂号询问
            if ("直接挂号".equals(analysisResult.getIntent())) {
                logger.info("检测到直接挂号询问 - 用户ID: {}, 将跳过症状详细收集", userId);
                shouldSkipSymptomCollection = true;
                directRecommendation = true;
            }
            
            // 构建完整的对话历史（基于实时数据，避免重复添加）
            List<String> updatedHistory = new java.util.ArrayList<>(realTimeHistory);
            
            // 检查是否已经包含当前用户输入
            String currentUserInput = "用户: " + query;
            if (!updatedHistory.contains(currentUserInput)) {
                updatedHistory.add(currentUserInput);
                logger.info("添加用户输入到对话历史: {}", currentUserInput);
            } else {
                logger.info("用户输入已存在，跳过重复添加");
            }
            
            Map<String, Object> result = new HashMap<>();
            result.put("intentType", analysisResult.getIntent());
            result.put("confidence", analysisResult.getConfidence());
            result.put("reason", analysisResult.getReason());
            result.put("keywords", analysisResult.getKeywords());
            result.put("medicalTerms", analysisResult.getMedicalTerms());
            result.put("riskLevel", analysisResult.getRiskLevel());
            result.put("fullAiAnalysis", analysisResult.isFullAiAnalysis());
            result.put("conversationHistory", updatedHistory);
            result.put("shouldSkipSymptomCollection", shouldSkipSymptomCollection);
            result.put("directRecommendation", directRecommendation);
            result.put("conversationStage", conversationStage);
            result.put("nextAction", nextAction);
            
            logger.info("意图识别完成 - 用户ID: {}, 最终意图: {}, AI分析: {}, 直接推荐: {}", 
                    userId, analysisResult.getIntent(), analysisResult.isFullAiAnalysis(), directRecommendation);
            
            return result;
            
        } catch (Exception e) {
            logger.error("意图识别服务失败 - 用户ID: {}, 错误: {}", userId, e.getMessage(), e);
            
            // 构建对话历史（基于实时数据，备用逻辑）
            List<String> updatedHistory = new java.util.ArrayList<>(realTimeHistory);
            String currentUserInput = "用户: " + query;
            if (!updatedHistory.contains(currentUserInput)) {
                updatedHistory.add(currentUserInput);
            }
            
            Map<String, Object> result = new HashMap<>();
            result.put("intentType", "有意图");
            result.put("confidence", 0.5);
            result.put("reason", "服务异常，默认判断为有意图");
            result.put("error", e.getMessage());
            result.put("fallback", true);
            result.put("conversationHistory", updatedHistory);
            
            logger.warn("使用默认意图识别结果 - 有意图");
            return result;
        }
    }
}